import sys
import os
import yaml
from langchain_openai import ChatOpenAI

# Agent maximum recursion limit
RECURSION_LIMIT = 50

# 功能开关和全局变量（先定义默认值）
JAVA_HOME = ""
JAVA_VERSION = ""
MAVEN_HOME = ""
Neo4j_URI = ""
Neo4j_User = ""
Neo4j_Password = ""
OPENAI_API_BASE = ""
OPENAI_API_KEY = ""
MODEL_NAME = "gpt-3.5-turbo"
llm = None
Enable_Native_Function_Call = False
Limit_Retrieve_Test_Case = True
CKGConstruction_Jar_Path = ""


def load_config():
    """
    读取外部 config.yaml 配置文件，并初始化全局变量和 LLM
    """
    global JAVA_HOME, JAVA_VERSION, MAVEN_HOME
    global Neo4j_URI, Neo4j_User, Neo4j_Password
    global OPENAI_API_BASE, OPENAI_API_KEY, MODEL_NAME, llm
    global Enable_Native_Function_Call, Limit_Retrieve_Test_Case
    global CKGConstruction_Jar_Path

    # 获取 exe 或源码目录
    if getattr(sys, "frozen", False):
        base_dir = os.path.dirname(sys.executable)
    else:
        base_dir = os.path.dirname(os.path.abspath(__file__))

    # 配置文件路径
    config_path = os.path.join(base_dir, "config.yaml")
    if not os.path.exists(config_path):
        raise FileNotFoundError(f"Config file not found: {config_path}")

    # 读取配置
    with open(config_path, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f)

    # 基础路径和参数
    JAVA_HOME = config.get("JAVA_HOME", JAVA_HOME)
    JAVA_VERSION = config.get("JAVA_VERSION", JAVA_VERSION)
    MAVEN_HOME = config.get("MAVEN_HOME", MAVEN_HOME)
    Neo4j_URI = config["Neo4j"]["uri"]
    Neo4j_User = config["Neo4j"]["user"]
    Neo4j_Password = config["Neo4j"]["password"]

    # OpenAI 配置
    OPENAI_API_BASE = config.get("OPENAI_API_BASE", "")
    OPENAI_API_KEY = config.get("OPENAI_API_KEY", "")
    MODEL_NAME = config.get("MODEL", MODEL_NAME)

    # 设置环境变量（保证 langchain 内部调用也能用）
    os.environ["OPENAI_API_BASE"] = OPENAI_API_BASE
    os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY

    # 初始化 LLM
    llm = ChatOpenAI(model=MODEL_NAME, temperature=0, api_key=OPENAI_API_KEY)

    # 功能开关
    Enable_Native_Function_Call = config.get("Enable_Native_Function_Call", False)
    Limit_Retrieve_Test_Case = True

    # 知识图谱构建包路径
    CKGConstruction_Jar_Path = os.path.join(base_dir, config.get("CKGConstruction_Jar_Path", ""))

    return config
